package com.zxh.weather.collection.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zxh.common.bean.YmlBean;
import com.zxh.common.utils.StringUtils;
import com.zxh.weather.collection.service.WeatherCollectionDataService;
import com.zxh.weather.collection.vo.WeatherResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * @author zxh
 * @Title: WeatherCollectionDataServiceImpl
 * @ProjectName eureka-collection
 * @Description: TODO
 * @date 2018/10/2220:43
 */
@Service
@Slf4j
public class WeatherCollectionDataServiceImpl implements WeatherCollectionDataService {
    @Autowired
    private YmlBean ymlConfig;

    public RestTemplate restTemplate=new RestTemplate();

    @Override
    @CachePut(value = "user", key = "#code" )
    public WeatherResponse saveDateWeatherData(String code) {
        log.info("正在存入缓存："+code);
        String url="";
        if(StringUtils.isNumeric(code)){
            url =ymlConfig.getWeatherUrl()+"?citykey="+code;
        }else {
            url=ymlConfig.getWeatherUrl()+"?city="+code;
        }

       return getForEntity(url);
    }
   /**
     　　* @Description:抽取通用方法
     　　* @param id
     　　* @return WeatherResponse
     　　* @throws
     　　* @author zxh
     　　* @date 2018/10/16 10:13
     　　*/
    private   WeatherResponse getForEntity(String url){
        //log.info("没有使用缓存");
        //restTemplate方法 获取url 返回的值
        ResponseEntity<String>
                responseEntity=restTemplate.getForEntity(url,String.class);
        String body=null;
        //判断是否返回成功
        if(responseEntity.getStatusCodeValue()==200){
            body=responseEntity.getBody();
        }
        //json 转对象 ObjectMapper springboot -start 内置对象
        ObjectMapper mapper=new ObjectMapper();
        WeatherResponse response =null;
        try {
            response=mapper.readValue(body, WeatherResponse.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
}
